from flask import Blueprint,request,make_response,jsonify,redirect,json
import requests
import random
from application.models.users.user import *
from application.models.users.user import db
from utils.com import get_ali_object
# from db import db
import time
from utils.Myjwt import myjwt
gou_blue = Blueprint("gouwu",__name__)
@gou_blue.route('/tianjia',methods=['POST'])
def tianjia():
    data = json.loads(request.data)
    uid = data['uid']
    kid = data['kid']
    shu = data['count']
    is_check  = 20* int(shu)
    k = Orders.query.filter_by(courseid=kid).first()
    if k:
        if k.courseid == kid:
            return jsonify({'code':400,'msg':'已经购买过了'})
    c = Cart(userid=uid,cid=kid,count=shu,is_check=is_check)
    db.session.add(c)
    db.session.commit()
    return jsonify({'code':200,'msg':'加入购物车成功'})
@gou_blue.route('/gouwuzhan')
def gouwuzhan():
    uid = request.args.get('userid')
    k = Cart.query.filter_by(userid=uid).all()
    list = []
    for i in k:
        o = Course.query.filter_by(id=int(i.cid)).all()
        for i in o:
            list.append({
                'id': i.id,
                'name':i.name,
                'url':i.url,
                'descrip':i.descrip
            })
    print("res",)
    return jsonify({'code':200,'data':list})
@gou_blue.route('/gouwugoumai',methods=['POST'])
def gouwumai():
    data = json.loads(request.data)
    userid = data['userid']
    courseid = data['courseid']
    number = 1
    price = 200
    tmoney = 200
    order_no = str(int(time.time())) + str(userid) + str(random.randint(100, 999))
    k = Orders(order_no=order_no,userid=userid,courseid=courseid,number=number,price=price,tmoney=tmoney,status=1)
    db.session.add(k)
    db.session.commit()
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=str(userid),  # 商品简单描述
        out_trade_no=order_no,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(tmoney),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code': 200, 'url': pay_url})
@gou_blue.route('/callback11')
def call():
    # 接收参数
    data = request.args
    datames = {k:v for k,v in data.items()}
    # 删除字典中key为sign的记录
    sign = datames.pop('sign')
    # 鉴权 订单号 流水号
    pay = get_ali_object()
    flag = pay.verify(datames,sign)
    if flag == True:
        # try:
        order_no = request.args.get('out_trade_no')
        trade_no = request.args.get('trade_no')
        print('lllll',order_no)
        print('22222',trade_no)
        k = Orders.query.filter_by(order_no=order_no).first()
        k.status = 2
        k.trans_no= trade_no
        # d = Cart.query.filter_by(cid=k.courseid).delect()
        # db.session.add(d)
        db.session.commit()
    return redirect("http://localhost:8080/#/gou")
# # 训练营课程
@gou_blue.route('/zhanshia')
def zhanshia():
    list = []
    o = Tcourse.query.all()
    for i in o:
        list.append({
            'id': i.id,
            'title': i.title,
            'url': i.url,
            'price': i.price,
            'intro': i.intro
        })
    return jsonify({'code': 200, 'data': list})

# 添加购物车
@gou_blue.route('/addcart',methods=['POST'])
def addcart():
    data = json.loads(request.data)
    userid = int(data['userid'])
    print('kmjfu',userid)
    cid = int(data['cid'])
    print('kmjfu', cid)
    cart = Cart.query.filter_by(cid=cid).first()
    if cart:
        # sql = "update cart set count=count+1 where cart.cid=%d"%int((cid))
        sql = Cart.query.filter_by(cid=cid).first()
        sql.count +=1
        db.session.commit()
        return jsonify({"code":200,'msg':'加入购物车成功'})
    else:
        count = 1
        sql1 =Cart(userid=userid,cid=cid,count=count)
        # sql1 = "insert into cart(userid,cid,count) values(%d,%d,%d)"%(int(userid),int(cid),int(count))
        db.session.add(sql1)
        db.session.commit()
        return jsonify({"code": 200, "msg": "加入购物车成功"})

# 我的购物车
@gou_blue.route("/gettcourse")
def getcart():
    userid = request.args.get("userid")
    cartlist = []
    tmoney = 0
    cid = 0
    sql = "select * from cart where cart.userid=%d"% int(userid)
    res = db.session.execute(sql)
    print('1111111111',res)
    for i in res:
        print('1455455',i['cid'])
        sql = "select * from tcourse where tcourse.id=%d"%int(i['cid'])
        res = db.session.execute(sql)
        print('444444444444',res)
        for j in res:
            d ={
                "id":j["id"],
                "title":j["title"],
                "price":j["price"],
                "url":j["url"],
                "count":i["count"],
                "amount":(j["price"] * i["count"])
            }
            cartlist.append(d)
            tmoney = j["price"] * i["count"]
            cid = j[cid]

    return jsonify({"code": 200, "msg":"ok","cartlist": cartlist,"tmoney":tmoney,'cid':cid})

# 购物车数量加
@gou_blue.route('/addcount',methods=["POST"])
def Add_count():
    req = json.loads(request.data)
    userid = req['userid']
    id = req['id']
    res = Cart.query.filter(Cart.userid==userid,Cart.cid==id).first()
    if res:
        counts = res.count+1
        res.count = counts
        db.session.commit()
    return jsonify({'code':200,'msg':'ok'})
def add():
    rek  =json.loads(request.data)

# 购物车数量减
@gou_blue.route('/mincount',methods=["POST"])
def Min_count():
    req = json.loads(request.data)
    userid = int(req['userid'])
    id = int(req['id'])
    res = Cart.query.filter(Cart.userid==userid,Cart.cid==id).first()
    if res:
        counts = res.count-1
        res.count = counts
        db.session.commit()
    return jsonify({'code':200,'msg':'ok'})
# 提交订单

@gou_blue.route("/pay",methods=["POST"])
def pay():
    data=json.loads(request.data)
    userid=int(data["userid"])
    tmoney=int(data["tmoney"])
    cid=int(data["cid"])
    sum=0
    sql = "select * from cart where userid=%d" % userid
    res=db.session.execute(sql)
    if not res:
        return jsonify({"code":500,"msg":"没有该商品"})
    sum+=float(tmoney)
    print(sum)
    # 订单号
    number = int(str(userid) + str(random.randint(1000, 9999)))
    create_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    update_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    status = 1
    try:
        isql = Orders(create_time=create_time,update_time=update_time,userid=userid,courseid=cid,number=number,tmoney=sum,status=status,price=sum)
        db.session.add(isql)
        sqlcart = Cart.query.filter(Cart.userid==userid).first()
        db.session.delete(sqlcart)
        print(">><<")
        db.session.commit()

    except:
        db.session.rollback()
    # 支付
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=str(userid) + "购买课程",  # 商品简单描述
        out_trade_no=number,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=sum,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })
@gou_blue.route("/callback")
def callback():
    data = request.args
    datames = {k: v for k, v in data.items()}
    # 删除字典中key为sign的记录
    sign = datames.pop('sign')
    # 鉴权 订单号 流水号
    pay = get_ali_object()
    flag = pay.verify(datames, sign)
    if flag == True:
        # try:
        order_no = request.args.get('out_trade_no')
        trade_no = request.args.get('trade_no')
        print('lllll', order_no)
        print('22222', trade_no)
        k = Orders.query.filter_by(number=order_no).first()
        print('41545',k)
        k.status = 2
        k.trans_no = trade_no
        d = Cart.query.filter_by(cid=k.courseid)
        d.delete()
        db.session.commit()
    return redirect("http://localhost:8080/#/cart1")
